﻿using MaterialDesignThemes.Wpf;
using project.B12.application.Ioc;
using project.B12.IService;
using project.B12.Model.Enums;
using project.B12.Model.Models;
using project.B12.Model.Res;
using project.B12.Service;
using software.Common.MVVM;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace project.B12.application.ViewModels.Dialogs
{
    public class AddPlateIdViewModel:ObservableObject
    {
        private string plateId;
        public string PlateId
        {
            get { return plateId; }
            set
            {
                plateId = value;
                this.RaisePropertyChanged();
            }
        }

        private string plateIDTip { get; set; }
        public string PlateIDTip
        {
            get { return plateIDTip; }
            set
            {
                plateIDTip = value;
                this.RaisePropertyChanged();
            }
        }

        private List<string> sampleTypes = new List<string>();
        public List<string> SampleTypes
        {
            get { return sampleTypes; }
            set { sampleTypes = value; this.RaisePropertyChanged(); }
        }

        private string sampleType;
        public string SampleType
        {
            get { return sampleType; }
            set
            {
                sampleType = value;
                this.RaisePropertyChanged();
            }
        }

        private string tip;
        public string Tip
        {
            get { return tip; }
            set
            {
                tip = value;
                this.RaisePropertyChanged();
            }
        }

        private int shelf;
        public int Shelf
        {
            get { return shelf; }
            set
            {
                shelf = value;
                this.RaisePropertyChanged();
            }
        }

        private int index;
        public int Index
        {
            get { return index; }
            set
            {
                index = value;
                this.RaisePropertyChanged();
            }
        }

        private string pattern = @"^[a-zA-Z0-9_\-+]+$";

        private IMICPlateMes _mICPlateMes { get; set; }

        private IServiceDevice _serviceDevice;

        public event Action<List<string>,int> ReturnPlate;

        public event Action<List<string>> ReturnPlateContinue;

        public event Action ConfirmDelete;

        public RelayCommand Close => new RelayCommand(ClosePlate);

        public RelayCommand WritePlateId => new RelayCommand(ConfirmPlateId);

        public RelayCommand Continue => new RelayCommand(ContinueAdd);

        public RelayCommand Delete => new RelayCommand(DeletePlate);

        public AddPlateIdViewModel(IMICPlateMes mICPlateMes, 
            IServiceDevice serviceDevice)
        {
            _mICPlateMes= mICPlateMes;
            _serviceDevice= serviceDevice;
            PlateIDTip = "只允许输入数字，大小写字母，符号'_''-''+'";
        }

        private void ConfirmPlateId()
        {
            if (!CheckPlate())
                return;

            string id = PlateId;
            List<string> samples = new List<string>()
            {
                id,
                sampleType.ToString()
            };

            ReturnPlate.Invoke(samples,Index);
        }

        private void ContinueAdd()
        {
            if (!CheckPlate())
                return;

            string id = PlateId;
            List<string> samples = new List<string>()
            {
                id,
                sampleType.ToString(),
                Shelf.ToString(),
                index.ToString()
            };
            ReturnPlateContinue.Invoke(samples);

            Table_MonitorMes temp= new Table_MonitorMes();
            var next = _serviceDevice.Items64.Where(o => o.Shelf == shelf && o.Index > index && o.State == HoleState.NULL);
            if(next==null||next.Count()==0)
            {
                var nextTemp= _serviceDevice.Items64.Where(o =>o.State == HoleState.NULL&&o.Shelf>shelf);
                if(nextTemp==null|| nextTemp.Count()==0)
                {
                    if(!_serviceDevice.Items64.Any(o => o.State == HoleState.NULL && o.Shelf < shelf))
                    {
                        WPF.Controls.Message.Push("当前已没有位置可添加板", MessageBoxImage.Warning);
                        return;
                    }
                    nextTemp = _serviceDevice.Items64.Where(o => o.State == HoleState.NULL && o.Shelf < shelf);
                    temp = nextTemp.OrderBy(o => o.Shelf).ThenBy(o => o.Index).FirstOrDefault();
                }
                else
                {
                     temp = nextTemp.OrderBy(o => o.Shelf).ThenBy(o => o.Index).FirstOrDefault();
                }
            }
            else
            {
                 temp = next.OrderBy(o => o.Index).FirstOrDefault();
            }
            Shelf = temp.Shelf;
            Index = temp.Index;
            PlateId=string.Empty;
            Tip = string.Empty;
        }

        private bool CheckPlate()
        {
            if (string.IsNullOrEmpty(PlateId))
            {
                Tip = Resources.PlateIdEmptyWarning;
                return false;
            }
            if (string.IsNullOrEmpty(SampleType))
            {
                Tip = Resources.PlateTypeWarning;
                return false;
            }
            if (!Regex.IsMatch(PlateId, pattern))
            {
                Tip = Resources.PlateIDRules;
                return false;
            }

            var imageNames = ViewModelLocator.AnalyseViewModel.WellPlateIDList;
            List<string> names = new List<string>();
            foreach (var name in imageNames)
            {
                int index = name.IndexOf('&');
                names.Add(name.Substring(index + 1));
            }

            if (_serviceDevice.Items64.Where(o => o.PlateID == PlateId && o.PlateType == SampleType).Count() > 0 ||
                names.Contains(PlateId))
            {
                PlateId = PlateId + DateTime.Now.ToString("yyyyMMddHHmmss");
            }
            return true;
        }

        /// <summary>
        /// 删除板
        /// </summary>
        private void DeletePlate()
        {
            MessageBoxResult result = MessageBox.Show("是否删除该板？", "提示", MessageBoxButton.OKCancel, MessageBoxImage.Question);
            if(result == MessageBoxResult.OK)
            {
                ConfirmDelete.Invoke();
                return;
            }
        }

        private void ClosePlate()
        {
            if (DialogHost.IsDialogOpen("Main"))
                DialogHost.Close("Main", true);
        }
    }
}
